package services

import (
	"base_server/internal/models/cutpart"
	"base_server/internal/models/fashion"
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/parnurzeal/gorequest"
	common "jihe.common"
	"jihe.common/oss"
	"jihe.common/protos/base_server"
	"jihe.common/protos/base_server/proto"
	"jihe.common/protos/calculate_server"
	calculate_server_proto "jihe.common/protos/calculate_server/proto"
	"jihe.common/tool"
	"strings"
	"time"
)

func BatchCreateFashionConsume() {
	redisClient := new(common.Redis)
	_ = redisClient.Consume(redisClient.GetBaseBatchCreateFashionConsumeKey(), func(bs []byte) {
		defer redisClient.Get().Decr(redisClient.GetBaseBatchCreateFashionLastNumKey())
		pgSql := new(common.Pgsql)
		tx, err := pgSql.Get().Begin()
		if err != nil {
			common.Loger.Error("%v", err)
			return
		}
		baseFashion := proto.BaseFashion{}
		err = json.Unmarshal(bs, &baseFashion)
		if err != nil {
			common.Loger.Error("%v", err)
			return
		}
		fashionTbl := fashion.NewTx(tx)
		cuts, err := tool.SplitObj(baseFashion.ObjUrl)
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}
		baseFashion.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
		cutpartTbl := cutpart.NewTx(tx)
		err = cutpartTbl.BatchCreate(&proto.BaseCutparts{FashionId: baseFashion.Id, BaseCutpartList: cuts})
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}
		vtInfos := make([]base_server.VtInfo, 0)
		for _, v := range cuts {
			item := base_server.VtInfo{}
			res, err := calculate_server.GetBorderNode(context.Background(), &calculate_server_proto.GetBorderNodeReq{ObjUrl: v.ObjUrl})
			if err != nil {
				_ = tx.Rollback()
				common.Loger.Error("%v", err)
				return
			}
			err = json.Unmarshal([]byte(res.Stdout), &item)
			if err != nil {
				common.Loger.Error("%v", err)
				_ = tx.Rollback()
				return
			}
			item.Code = v.Code
			vtInfos = append(vtInfos, item)
		}

		for dx, v := range cuts {
			getDxfInfoReq := base_server.DxfInfoReq{}
			getDxfInfoReq.CpName = v.Code
			getDxfInfoReq.DxfPath = strings.Replace(baseFashion.DxfUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)
			getDxfInfoReq.ResourcePath = strings.Replace(v.ObjUrl, "files.dizanz", "jihe-file.oss-cn-beijing-internal.aliyuncs", -1)
			getDxfInfoReqByte, _ := json.Marshal(getDxfInfoReq)
			dxfInfoRet, err := calculate_server.GetDxfInfo(context.Background(), &calculate_server_proto.GetDxfInfoReq{
				Base64: base64.StdEncoding.EncodeToString(getDxfInfoReqByte),
			})
			if err != nil {
				_ = tx.Rollback()
				common.Loger.Error("%v", err)
				return
			}
			dxfInfo := base_server.DxfInfo{}
			err = json.Unmarshal([]byte(dxfInfoRet.Stdout), &dxfInfo)
			if err != nil {
				_ = tx.Rollback()
				common.Loger.Error("%v", err)
				return
			}
			if dx == 0 {
				baseFashion.AlgorithmParam = &proto.BaseFashionAlgorithmParam{UvWidth: fmt.Sprintf("%v", dxfInfo.UvcloLength)}
			}
			for dx, item := range vtInfos {
				if item.Code == v.Code {
					vtInfos[dx].DxfInfo = dxfInfo
				}
			}
		}
		bucket, err := oss.GetClient().Bucket("jihe-file")
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}
		jsonByte, err := json.Marshal(vtInfos)
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}

		fileName := fmt.Sprintf("%s/%d.json", time.Now().Format("2006-01-02"), tool.GetSnowflakeId())
		err = bucket.PutObject(fileName, bytes.NewReader(jsonByte))
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}
		baseFashion.CutpartBorderPoint = "https://files.dizanz.com/" + fileName
		if baseFashion.SuperFashionId != "" { //复制父级工艺
			superCraftUrl := fmt.Sprintf("%s/%s_crafts/%s.json?%d", common.Configer.Oss.Domain, common.Configer.Runmode, baseFashion.SuperFashionId, tool.GetSnowflakeId())
			tool.GetRequest().Get(superCraftUrl).Timeout(time.Second * 10).EndBytes(func(response gorequest.Response, body []byte, errs []error) {
				if response.StatusCode == 200 && len(errs) == 0 {
					currentCraftUrl := fmt.Sprintf("%s_crafts/%s.json", common.Configer.Runmode, baseFashion.Id)
					err = bucket.PutObject(currentCraftUrl, bytes.NewReader(body))
					if err != nil {
						common.Loger.Error("%v", err)
					}
				}
			})
		}
		err = fashionTbl.Create(&baseFashion)
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}
		err = tx.Commit()
		if err != nil {
			_ = tx.Rollback()
			common.Loger.Error("%v", err)
			return
		}

	})
}
